const html = String.raw;

/* 事件委托（代理） */
export function _on(type, methods, ac = "action") {
  document.addEventListener(type, async (e) => {
    const action = e.target.dataset[ac];
    if (action === undefined) return;
    if (methods[action] === undefined) return;
    methods[action].call(e.target);
  });
}

/* _confirm 组件 */
export function _confirm(title = "", content = "") {
  const html = String.raw;
  const str = html` <div class="modal fade" id="_CONFIRM">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5">${title}</h1>
        </div>
        <div class="modal-body">${content}</div>
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-primary"
            onclick="_CONFIRM_YES()"
          >
            确定
          </button>
          <button
            type="button"
            class="btn btn-secondary"
            onclick="_CONFIRM_NO()"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  </div>`;

  // 插入到body
  document.body.insertAdjacentHTML("beforeend", str);

  // 显示对话框
  const myModal = new bootstrap.Modal("#_CONFIRM", {
    backdrop: "static",
    keyboard: false,
  });
  myModal.show();
  return new Promise((resolve) => {
    // 全局确定、取消函数
    window._CONFIRM_YES = function () {
      resolve(true);
      myModal.hide();
    };
    window._CONFIRM_NO = function () {
      resolve(false);
      myModal.hide();
    };
  });
}

/* _dialog 组件 */
export function _dialog(title = "", content = "", footer = "") {
  const _DIALOG_ID = `_DIALOG_${Math.ceil(Math.random() * 1000000)}`;
  const str = html`<div class="modal fade" id="${_DIALOG_ID}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5">${title}</h1>
        </div>
        <div class="modal-body p-4">${content}</div>
        <div class="modal-footer">${footer}</div>
      </div>
    </div>
  </div>`;

  // 插入到body
  document.body.insertAdjacentHTML("beforeend", str);

  // 显示对话框
  const myModal = new bootstrap.Modal(`#${_DIALOG_ID}`, {
    backdrop: "static",
    keyboard: false,
  });
  return myModal;
}

/* _validForm */
export function _validForm(obj, cb) {
  const r = cb(obj.value);
  if (r) {
    obj.classList.remove("is-invalid");
    obj.classList.add("is-valid");
  } else {
    obj.classList.remove("is-valid");
    obj.classList.add("is-invalid");
  }
  return r;
}

/* 分页 */
// 10 [1,2,3,4,5,6,7,8,9,10]

// console.log(new Array(10).fill(1).map((el, index) => index + 1));

export function _pagination(totalPages, page = 1, action = "changePage") {
  // 生成分页
  const totalPagesArr = new Array(totalPages).fill(0).map((_, i) => i + 1);
  return html`
    <ul class="pagination">
      <li class="page-item ${page === 1 ? "disabled" : ""}">
        <a
          data-action="${action}"
          data-page="${page - 1}"
          class="page-link"
          href="#"
          >上一页</a
        >
      </li>
      ${totalPagesArr
        .map(
          (el) =>
            html` <li class="page-item ${el === page ? "active" : ""}">
              <a
                data-action="${action}"
                data-page="${el}"
                class="page-link"
                href="#"
                >${el}</a
              >
            </li>`
        )
        .join("")}
      <li class="page-item ${page === totalPages ? "disabled" : ""}">
        <a
          data-action="${action}"
          data-page="${page + 1}"
          class="page-link"
          href="#"
          >下一页</a
        >
      </li>
    </ul>
  `;
}

/*  */

export function _treeTable(data = [], res = [], pid = "", deep = 0) {
  data.forEach((el) => {
    if (el.pid === pid) {
      el.deep = deep;
      // 是否是叶子节点
      el.isDeaf = data.find((x) => x.pid === el.id) == null;
      res.push(el);
      _treeTable(data, res, el.id, deep + 1);
    }
  });
  return res;
}
